package utils.io;

import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
import java.util.LinkedList;
import java.util.List;

import utils.Display;

import kb.DescriptionLogicsKB;


/**
 * A list of queries w.r.t. the stipulated syntax, given by users or derived
 * from user logs
 * 
 * @see Syntax Guide
 * @author j55wu
 * 
 */
public class QueryAccess {

	public static List<Object[]> getQueries(String filename,
			DescriptionLogicsKB kb) {
		List<Object[]> querylines = null;
		FileReader fr = null;
		BufferedReader in = null;
		try {
			fr = new FileReader(filename);
			in = new BufferedReader(fr);
			querylines = getQueries(in, kb);
			in.close();
			fr.close();
		} catch (Exception e) {

		}
		return querylines;
		// done
	}

	public static List<Object[]> getQueries(BufferedReader in,
			DescriptionLogicsKB kb) throws IOException {
		List<Object[]> querylines = new LinkedList<Object[]>();
		String line = null;
		while ((line = in.readLine()) != null) {
			line = line.trim();
			if (line.equals("") || line.startsWith(Display.COMMENTS)
					|| !line.startsWith(Display.QUERYSYMBOL)) {
				continue;
			}
			// process lines
			line = line.substring(line.lastIndexOf(Display.QUERYSYMBOL) + 1)
					.trim();
			querylines.add(parseQueryLine(line, kb));
		}
		return querylines;
	}

	// refer to the syntax guide: Q-id C Pd
	@Deprecated
	public static Object[] parseQueryLine(String qline, DescriptionLogicsKB kb) {
		Object[] res = new Object[3];
		// qline = qline.trim();
		// LinkedList<LinkedList<String>> subs =
		// Parser.breakListByMatchingBrackets(
		// Parser.getListOfTokensFromTokenizer(qline));
		// if(subs.size()!=3){
		// System.err.println("#arguments must be 3, e.g., Q1 C Pd "+qline);
		// throw new RuntimeException();
		// }
		// //query id found
		// res[0] = Parser.tokensAsString(subs.get(0));
		// //query itself
		// try {
		// res[1] = Parser.parseAlgebraQuery(subs.get(1));
		// } catch (SyntaxParsingException e1) {
		// // TODO Auto-generated catch block
		// e1.printStackTrace();
		// }
		// if(subs.size() == 3){
		// try {
		// res[2] = Parser.createOrderingDescription(subs.get(2), kb);
		// } catch (SyntaxParsingException e) {
		// // TODO Auto-generated catch block
		// e.printStackTrace();
		// }
		//
		// }else{
		// res[2] = null;
		// }
		return res;
	}

}
